<template>
  <div>
    <a-modal
      :visible="visible"
      :title="title"
      @ok="handleOk"
      @cancel="handleCancel"
      :width="1000"
    >
      <div class="user-select-container">
        <!-- 顶部搜索区域 -->
        <div class="search-area">
        <a-input-search
          :value="searchText"
          placeholder="搜索用户名或真实姓名"
            style="width: 300px"
          @search="handleSearch"
          @update:value="val => searchText = val"
            allow-clear
        />
          <a-button @click="handleRefresh" :loading="loading">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
        </div>

        <!-- 主体区域 - 分屏布局 -->
        <div class="content-area">
          <!-- 左侧部门树 -->
          <div class="dept-tree-section">
            <div class="section-header">
              <span class="section-title">组织架构</span>
            </div>
            <div class="dept-tree-container">
              <a-input-search 
                :value="deptSearchText"
                @update:value="val => deptSearchText = val"
                placeholder="搜索部门" 
                size="small" 
                style="margin-bottom: 8px"
              />
              <a-spin :spinning="deptLoading">
                <a-tree
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :tree-data="filteredDeptTree"
                  :field-names="{ key: 'id', title: 'deptName' }"
                  @select="onDeptSelect"
                  @expand="onExpand"
                  :selected-keys="selectedDeptKeys"
                >
                  <template #title="{ deptName }">
                    <span v-if="deptName.indexOf(deptSearchText) > -1">
                      {{ deptName.substring(0, deptName.indexOf(deptSearchText)) }}
                      <span style="color: #f50">{{ deptSearchText }}</span>
                      {{ deptName.substring(deptName.indexOf(deptSearchText) + deptSearchText.length) }}
                    </span>
                    <span v-else>{{ deptName }}</span>
                  </template>
                </a-tree>
              </a-spin>
            </div>
          </div>

          <!-- 右侧用户列表 -->
          <div class="user-list-section">
            <div class="section-header">
              <span class="section-title">
                {{ selectedDeptName ? `${selectedDeptName} - 人员列表` : '全部人员' }}
              </span>
              <span class="user-count">(共 {{ filteredUsers.length }} 人)</span>
            </div>
        
            <div class="user-list-container">
              <a-spin :spinning="loading">
                <!-- 单选模式 -->
                <a-radio-group 
                  v-if="!multiple" 
                  :value="selectedUser" 
                  class="user-list" 
                  @update:value="val => selectedUser = val"
                >
            <div v-for="user in filteredUsers" :key="user.id" class="user-item">
              <a-radio :value="user.id">
                    <div class="user-info">
                      <div class="user-name">{{ user.realName || user.userName }}</div>
                      <div class="user-meta">
                        <span v-if="user.deptName" class="dept-tag">{{ user.deptName }}</span>
                        <span v-if="user.mobile" class="mobile">{{ user.mobile }}</span>
                      </div>
                    </div>
              </a-radio>
                </div>
                </a-radio-group>

                <!-- 多选模式 -->
                <a-checkbox-group 
                  v-else 
                  :value="selectedUsers" 
                  class="user-list" 
                  @update:value="val => selectedUsers = val"
                >
            <div v-for="user in filteredUsers" :key="user.id" class="user-item">
              <a-checkbox :value="user.id">
                    <div class="user-info">
                      <div class="user-name">{{ user.realName || user.userName }}</div>
                      <div class="user-meta">
                        <span v-if="user.deptName" class="dept-tag">{{ user.deptName }}</span>
                        <span v-if="user.mobile" class="mobile">{{ user.mobile }}</span>
                      </div>
                    </div>
              </a-checkbox>
            </div>
          </a-checkbox-group>

              <!-- 空状态 -->
              <div v-if="!loading && filteredUsers.length === 0" class="empty-state">
                <a-empty description="暂无人员数据" />
              </div>
        </a-spin>
            </div>
          </div>
        </div>

        <!-- 底部选中状态 -->
        <div v-if="multiple && selectedUsers.length > 0" class="selected-info">
          <span>已选择 {{ selectedUsers.length }} 人：</span>
          <a-tag 
            v-for="userId in selectedUsers.slice(0, 5)" 
            :key="userId" 
            closable 
            @close="removeSelectedUser(userId)"
            style="margin: 2px"
          >
            {{ getUserDisplayName(userId) }}
          </a-tag>
          <span v-if="selectedUsers.length > 5">等{{ selectedUsers.length }}人</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import type { PropType } from 'vue';
import { users } from '@/api/apis/user';
import { message } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';
// @ts-ignore
import Api from '@/api';

interface User {
  id: string;
  userName: string;
  realName?: string;
  deptName?: string;
  mobile?: string;
  deptId?: string;
}

interface Department {
  id: string;
  deptName: string;
  supDeptId?: string;
  children?: Department[];
}

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    default: '选择用户'
  },
  multiple: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: [String, Array] as PropType<string | string[]>,
    default: undefined
  }
});

const emit = defineEmits(['update:visible', 'update:modelValue', 'ok', 'cancel']);

// 用户相关状态
const loading = ref(false);
const userList = ref<User[]>([]);
const searchText = ref('');
const selectedUser = ref<string>('');
const selectedUsers = ref<string[]>([]);

// 部门相关状态
const deptLoading = ref(false);
const deptList_data = ref<Department[]>([]);
const deptSearchText = ref('');
const selectedDeptId = ref<string>('');
const selectedDeptName = ref<string>('');
const selectedDeptKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);
const autoExpandParent = ref(true);

// 过滤部门树
const filteredDeptTree = computed(() => {
  if (!deptSearchText.value) {
    return deptList_data.value;
  }
  return filterDeptByKeyword(cloneDeep(deptList_data.value), deptSearchText.value);
});

// 根据搜索文本过滤用户列表
const filteredUsers = computed(() => {
  const search = searchText.value.toLowerCase();
  return userList.value.filter(user => 
    (user.userName?.toLowerCase().includes(search) || 
     user.realName?.toLowerCase().includes(search))
  );
});

// 过滤部门树的函数
const filterDeptByKeyword = (treeData: Department[], keyword: string): Department[] => {
  return treeData.filter((item) => {
    if (item.children?.length) {
      item.children = filterDeptByKeyword(item.children, keyword);
      if (item.children.length) {
        return true;
      }
    }
    return item.deptName?.includes(keyword);
  });
};

// 获取用户显示名称
const getUserDisplayName = (userId: string): string => {
  const user = userList.value.find(u => u.id === userId);
  return user ? (user.realName || user.userName) : userId;
};

// 移除选中的用户
const removeSelectedUser = (userId: string) => {
  selectedUsers.value = selectedUsers.value.filter(id => id !== userId);
};

// 加载部门列表
const loadDepartments = async () => {
  deptLoading.value = true;
  try {
    const depts = await Api.systemDept.deptList({});
    deptList_data.value = depts || [];
    // 默认展开第一级
    expandedKeys.value = depts?.map(dept => dept.id) || [];
  } catch (error) {
    message.error('获取部门列表失败');
  } finally {
    deptLoading.value = false;
  }
};

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  try {
    const { items = [] } = await users({
      index: 1,
      pageSize: 1000,
      key: searchText.value || undefined,
      deptId: selectedDeptId.value || undefined
    });
    userList.value = items;
  } catch (error) {
    message.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理部门选择
const onDeptSelect = (selectedKeys: string[]) => {
  if (selectedKeys.length > 0) {
    const deptId = selectedKeys[0];
    selectedDeptId.value = deptId;
    selectedDeptKeys.value = [deptId];
    
    // 查找部门名称
    const findDeptName = (depts: Department[], targetId: string): string => {
      for (const dept of depts) {
        if (dept.id === targetId) {
          return dept.deptName;
        }
        if (dept.children?.length) {
          const childResult = findDeptName(dept.children, targetId);
          if (childResult) return childResult;
        }
      }
      return '';
    };
    
    selectedDeptName.value = findDeptName(deptList_data.value, deptId);
  } else {
    selectedDeptId.value = '';
    selectedDeptName.value = '';
    selectedDeptKeys.value = [];
  }
  
  loadUsers();
};

// 处理部门树展开
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

// 处理搜索
const handleSearch = () => {
  loadUsers();
};

// 处理刷新
const handleRefresh = () => {
  loadUsers();
  loadDepartments();
};

// 处理确认
const handleOk = () => {
  const result = props.multiple ? selectedUsers.value : selectedUser.value;
  emit('update:modelValue', result);
  emit('ok', result);
  emit('update:visible', false);
};

// 处理取消
const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
};

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 加载数据
    loadDepartments();
    loadUsers();
    
    // 初始化选中值
    if (props.multiple) {
      selectedUsers.value = Array.isArray(props.modelValue) ? props.modelValue : [];
    } else {
      selectedUser.value = typeof props.modelValue === 'string' ? props.modelValue : '';
    }
  } else {
    // 清空状态
    searchText.value = '';
    deptSearchText.value = '';
    selectedDeptId.value = '';
    selectedDeptName.value = '';
    selectedDeptKeys.value = [];
    if (props.multiple) {
      selectedUsers.value = [];
    } else {
      selectedUser.value = '';
    }
  }
});
</script>

<style lang="less" scoped>
.user-select-container {
  .search-area {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
  }

  .content-area {
    display: flex;
    height: 500px;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    overflow: hidden;
  }

  .dept-tree-section {
    width: 280px;
    border-right: 1px solid #f0f0f0;
    display: flex;
    flex-direction: column;
  }

  .user-list-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0; /* 确保flex子元素可以正常滚动 */
  }

  .user-list-container {
    flex: 1;
    overflow: hidden; /* 防止内容溢出 */
    display: flex;
    flex-direction: column;
  }

  .section-header {
    padding: 12px 16px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .section-title {
      font-weight: 500;
      color: #262626;
    }

    .user-count {
      font-size: 12px;
      color: #8c8c8c;
    }
  }

  .dept-tree-container {
    flex: 1;
    padding: 12px;
    overflow-y: auto;
  }

  .user-list {
    flex: 1;
    padding: 12px 16px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 350px; /* 限制最大高度确保滚动生效 */
    min-height: 0; /* 允许flex子元素收缩 */
  }

  .user-item {
    padding: 12px;
    border-radius: 6px;
    border: 1px solid #f0f0f0;
    transition: all 0.3s;

    &:hover {
      background-color: #f9f9f9;
      border-color: #d9d9d9;
    }

    .user-info {
      margin-left: 8px;
    }

    .user-name {
      font-weight: 500;
      color: #262626;
      margin-bottom: 4px;
    }

    .user-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: #8c8c8c;

      .dept-tag {
        background: #f0f0f0;
        padding: 2px 6px;
        border-radius: 4px;
        color: #595959;
    }

      .mobile {
        color: #1890ff;
      }
    }
  }

  .empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .selected-info {
    margin-top: 16px;
    padding: 12px;
    background: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 6px;
    font-size: 14px;
    color: #52c41a;
  }
}
</style> 